#!/bin/bash
usage()
{
cat << EOF
OPTIONS:
      -a MYY		Wait MYY microseconds between packet sends
      -c CFGFILE	Load config from cfg-file CFGFILE
      -C 		Run connect before starting send on UDP-packets.
      -g 		Use the largest available recv or send parameters in TCP
      -i ADDRESS	Which address to bind to.
      -f OFFSET		Strip offset amount of bytes from header of each packet
      -l LAST_PACKET	number of last packet to be received
      -n IP		Simultaneously send stream to IP
      -u N		Multiply a TCP stream to use N different streams(must be same on both sides)
      -p SIZE		Expect SIZE size payload on packets. Reject everything else.
      -q DATATYPE	Receive DATATYPE type of data and resequence (DATATYPE: vdif, mark5b,udpmon,mark5bnet)
      -r RATE		Expected network rate in Mb/s(default: 10000)
      -s SOCKET		Socket number(Default: 2222)
      -S 		Write to a single file (bottlenecks unless used with a raid)
      -e POSIX_TIME	start event at START_TIME (time since epoch or anything the date command accepts)
      -t		Capture socket type (default: udpstream) options: (udpstream, tpstream, tcpsplice)
      -w		Wait for START_TIME in metadata before starting receive (End time will be moved accordingly)
      -v 		Verbose. Print stats on all transfers
      -y 		Force socket reaqcuire on error (Useful when recordings overlap)
EOF
}
SCRIPTNAME=vbs_queue
scriptPath=${0%$SCRIPTNAME}
if [ -z "$scriptPath" ]
then
  #invoked from PATH
  scriptPath=$(which $0)
  scriptPath=${scriptPath%$SCRIPTNAME}
fi
source ${scriptPath}vbs_common_functions

EXTRAOPS="#Schedule extra parameters"
RECALC_RATE=0
RECORD=1
n=1
while [ $# -gt 0 ]
do
  case $1 in
    -a) 
      EXTRAOPS="$EXTRAOPS
      wait_nanoseconds = $(($2*1000));"
      shift
      ;;
    -c)
      EXTRAOPS="$EXTRAOPS
      cfgfile = \"$2\";"
      shift
      ;;
    -C)
      EXTRAOPS="$EXTRAOPS
      connect_before_sending = 1;"
      shift
      ;;
    -i)
      EXTRAOPS="$EXTRAOPS
      address_to_bind_to = \"$2\";"
      shift
      ;;
    -f)
      EXTRAOPS="$EXTRAOPS
      offset = ${2};"
      shift
      ;;
    -u)
      EXTRAOPS="$EXTRAOPS
      stream_multiply = ${2};"
      shift
      ;;
    -g)
      EXTRAOPS="$EXTRAOPS
      use_largest_transac = 1;"
      ;;
    -l)
      EXTRAOPS="$EXTRAOPS
      last_packet = $2L;"
      shift
      ;;
    -m)
      if [ "$2" == "r" ]
      then
	RECORD=1
      else
	RECORD=0
      fi
      shift
      ;;
    -p)
      PACKETSIZEIS=$2
      EXTRAOPS="$EXTRAOPS
      packet_size = $(($2))L;"
      shift
      ;;
    -s)
      EXTRAOPS="$EXTRAOPS
      port = $2;"
      shift
      ;;
    -e)
      #DATDATE=$(date -d"$2" +%s 2> /dev/null)
      #if [ "$?" -ne 0 ]
      #then
	DATDATE=$(date -d"@${2}" +%s 2> /dev/null)
	if [ "$?" -ne 0 ]
	then
	  echo $(date --rfc-3339=seconds) "Error in setting startup date " | tee -a  $LOGFILE
	  usage
	  exit 1
	fi
      #fi
      EXTRAOPS="$EXTRAOPS
      starting_time = ${DATDATE}L;"
      shift
      ;;
    -t)
      EXTRAOPS="$EXTRAOPS
      capture = \"$2\";"
      shift
      ;;
    -v)
      EXTRAOPS="$EXTRAOPS
      verbose = 1;"
      ;;
    -n)
      EXTRAOPS="$EXTRAOPS
      hostname = \"$2\";"
      shift
      ;;
    -y)
      EXTRAOPS="$EXTRAOPS
      force_socket_reacquire = 1;"
      ;;
    -w)
      EXTRAOPS="$EXTRAOPS
      wait_start_on_metadata = 1;"
      ;;
    -q)
      EXTRAOPS="$EXTRAOPS
      datatype = \"$2\";"
      shift
      ;;
    -r)
      RECALC_RATE=1
      RATE=$2
      shift
      ;;
    -*) echo  $(date --rfc-3339=seconds) "Unknown argument $1";usage;exit 1; echo $(date --rfc-3339=seconds) "Errors in parameters of streaming $RECNAME" | tee -a  $LOGFILE ;;
  *) eval "arg_$n=$1";n=$(($n+1));;
esac
shift
done

RECNAME=$arg_1
#STIME=$arg_3
CONFSTART=""
YE_OLDE=$RECNAME

if [ "$RECALC_RATE" == "1" ]
then
  if [ -z "$PACKETSIZEIS" ]
  then
    PACKETSIZEIS=$(get_packetsize_from_cfgfile $CFGFILE)
    if [ "$?" -eq "$ERR" ]
    then
      echo "ERROR: No packet_size for $RECNAME found"
      exit 1
    fi
  fi
  NYY=$(echo "((1000000000)*$PACKETSIZEIS*8)/($RATE*1024*1024)" |bc )
  EXTRAOPS="$EXTRAOPS
  wait_nanoseconds = ${NYY};"
fi

if [ "$RECORD" -eq "1" ]
then
  kk=0
  #match=$(vbs_ls |egrep "^`echo ${RECNAME}`$")
  while [ ! -z "$(find ${ROOTDIRS}* -maxdepth 1 -name ${RECNAME})" ]
  #while [ -n "$match" ]
  do
    RECNAME=${YE_OLDE}_${kk}
    kk=$(($kk+1))
    echo $(date --rfc-3339=seconds) "Recording already exists! Renaming to $RECNAME" | tee -a  $LOGFILE
    #match=$(vbs_ls |egrep "^`echo ${RECNAME}`$")
  done
fi

if [ $RECORD -eq 0 ]
then
  DUR=$arg_2
  CONFSTART="hostname = \"$arg_2\";
  record = 0;"
else
  DUR=$arg_2
  CONFSTART="time = $(($DUR))L;
  record = 1;"
fi

if [ -z "$RECNAME" ] || [ -z "$DUR" ]
then
  echo $(date --rfc-3339=seconds) "Record name or destination/duration missing"
  usage
  echo $(date --rfc-3339=seconds) "Errors in parameters of streaming $RECNAME" >> $LOGFILE
  exit  1
fi

#A 12 char random string is used to identify a request
#stolen from http://nixcraft.com/shell-scripting/13454-command-generate-random-password-string.html
(
flock  -x 201
echo "`tr -dc A-Za-z < /dev/urandom |head -c 12` =
{
  filename = \"$RECNAME\";
  $CONFSTART
  $EXTRAOPS
};
" >> $SCHEDULE
) 201>$SCHEDLOCKFILE
if [ -z "${DATDATE}" ]
then
  DATDATE=$(date +%s)
fi

echo $LOGFILE
if [ "$RECORD" == "1" ]
then
  echo "`date --rfc-3339=seconds`: Added recording named $RECNAME to record for $DUR s starting at UTC:  $(date -u -d @${DATDATE} --rfc-3339=seconds) " | tee -a $LOGFILE
else
  echo "`date --rfc-3339=seconds`: Added streaming named $RECNAME to send to $DUR" starting at UTC:  $(date -u -d @${DATDATE} --rfc-3339=seconds) |tee -a  $LOGFILE
fi
#TODO: What date format people want?
exit 0
